#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define MAXLINE 4096

int main(int argc ,char **argv)
{
    int sockfd,n;//sockfd是一个client的描述符
    char recvline[4096],sendline[4096];
    struct sockaddr_in servaddr;//sockaddr_in:http://baike.baidu.com/view/2355183.htm
    
    if( argc !=2 )
    {
	    printf("usage:./client <ipaddress>\n");
     	exit(0);
    }
    
    if( (sockfd = socket(AF_INET,SOCK_STREAM,0))<0 )
    {	
	      printf("create socket error:%s(errno:%d)\n",strerror(errno),errno);
	      exit(0);
    }
    
    memset(&servaddr ,0 ,sizeof(servaddr) );
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(6666);
    if( inet_pton(AF_INET , argv[1],&servaddr.sin_addr )<=0 )
    {
	      printf("inet_pton error for %s\n",argv[1]);
	      exit(0);
    }
    
    if( connect(sockfd,(struct sockaddr *)&servaddr ,sizeof(servaddr) )<0)//建立链接
    {
	      printf("connect error: %s(errno:%d)\n",strerror(errno),errno);
	      exit(0);
    }
    while(1)//循环向服务器发送请求
    {
    	printf("send msg to server:");//向服务器发送信息
    	fgets(sendline, 4096,stdin);//gets(sendline);
    	if( send(sockfd ,sendline ,strlen(sendline),0 ) <0 )
    	{
		      printf("send msg error:%s(errno:%d)\n",strerror(errno),errno);
        	exit(0);
    	}
	
	n = recv(sockfd,recvline ,MAXLINE,0);//从服务器接收信息
	recvline[n]='\0';
	//fputs(buff , stdout);
	printf("recv msg from server:%s",recvline);
    }
    close(sockfd);
    exit(0);
}

